from django.utils.safestring import mark_safe
from django.urls import re_path
from django.db import transaction
from django.shortcuts import HttpResponse, render
from stark.service.s1 import StarkHandler, choice_display
from app_main import models
from app_main.forms.for_stark import CustomerPublicModelForm


class CustomerPublicHandler(StarkHandler):

    def follow_display(self, obj=None, is_head=None):
        if is_head:
            return '查看'

        follow_url = self.create_re_url('pub_follow', obj.id)
        return mark_safe('<a href="%s">跟进记录</a>' % follow_url)

    list_display = [
        StarkHandler.display_checkbox,
        'name',
        'contact',
        choice_display('状态', 'status'),
        follow_display,
        StarkHandler.display_edit,
        StarkHandler.display_del
    ]

    model_form_class = CustomerPublicModelForm

    def get_query_set(self, request, *args, **kwargs):
        first_q_set = self.model_class.objects.filter(consultant__isnull=True)
        return first_q_set

    def extra_urls(self):
        patterns = [
            re_path('(?P<nid>\d+)/follows/$', self.wrapper(self.pub_follow_view), name=self.get_url_name('pub_follow'))
        ]

        return patterns

    def pub_follow_view(self, request, nid):  # 查看公户的跟进记录
        f_list = models.FollowRecord.objects.filter(customer_id=nid)

        return render(request, 'app_main/pub_follow.html', {'f_list': f_list})

    def multi_distri_customer(self, request, *args, **kwargs):  # 批量分配公户到私户
        current_user_id = request.session['user_info']['id']
        id_list = request.POST.getlist('cb')
        current_p_customer_count = models.Customer.objects.filter(consultant_id=current_user_id, status=2).count()
        if (current_p_customer_count + len(id_list)) > models.Customer.MAX_PRIVATE_CUSTOMER:
            return HttpResponse('超出上限')
        else:
            flag = False
            with transaction.atomic():  # 事务
                origin_queryset = models.Customer.objects.filter(id__in=id_list, status=2,
                                                                 consultant__isnull=True).select_for_update()
                if len(origin_queryset) == len(id_list):
                    models.Customer.objects.filter(id__in=id_list, status=2,
                                                   consultant__isnull=True).update(consultant_id=current_user_id)
                    flag = True

            if not flag:
                return HttpResponse('一些客户已丢失，请重新选择')

    multi_distri_customer.text = '批量分配'

    action_list = [multi_distri_customer]
